package com.team.admin.auth;

import com.google.common.net.HttpHeaders;
import com.team.admin.domain.SystemUser;
import com.team.admin.service.AuthenticationJwtService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CustomerJwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private AuthenticationJwtService authenticationJwtService;

    private final static String TOKEN_PRE = "Bearer ";

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        String token = token(request);
        if(StringUtils.isBlank(token)){
            filterChain.doFilter(request,response);
            return;
        }

        UsernamePasswordAuthenticationToken authenticationToken
                = token(authenticationJwtService.jwtOfSystemUser(token));

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }


    private UsernamePasswordAuthenticationToken token(SystemUser systemUser){

        List<GrantedAuthority> grantedAuthorities = Collections.EMPTY_LIST;
        if(CollectionUtils.isNotEmpty(systemUser.getPermissions())){
            grantedAuthorities = systemUser.getPermissions().stream()
                    .map(p -> new SimpleGrantedAuthority(p)).collect(Collectors.toList());
        }
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(systemUser.getUserName(),null,grantedAuthorities);

        return token;
    }


    private String token(HttpServletRequest request){
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if(StringUtils.isBlank(token)){
            return null;
        }
        token = token.replace(TOKEN_PRE,"");
        return token;
    }
}
